package com.david.jetpack.workmanager

import android.content.Context
import android.util.Log
import androidx.work.*
import com.david.jetpack.JetPackApplication
import java.time.Duration

/**
 * 参考链接：https://www.jianshu.com/p/de19752f159c
 */
object WorkManagerTest {
    fun test() {
//        PeriodicWorkRequest 周期性的任务
        val constraints: Constraints = Constraints.Builder()
            .setRequiredNetworkType(NetworkType.UNMETERED)
            .setRequiresBatteryNotLow(true) //指定设备电池是否不应低于临界阈值
            .setRequiresCharging(true) //网络状态
            .setRequiresDeviceIdle(true) //指定{@link WorkRequest}运行时设备是否为空闲
            .setRequiresStorageNotLow(true) //指定设备可用存储是否不应低于临界阈值
//            .addContentUriTrigger(
//                myUri,
//                false
//            ) //指定内容{@link android.net.Uri}时是否应该运行{@link WorkRequest}更新
            .build()
        val data: Data = Data.Builder()
            .putString("params1", "first param")
            .putString("params2", "second param")
            .build()

        val request =
//            PeriodicWorkRequest.Builder(TestWorker::class.java, Duration.ofMinutes(15))
            OneTimeWorkRequest.Builder(TestWorker::class.java)
            .setConstraints(constraints)
            .setInputData(data)
            .addTag("test")
            .build()
        WorkManager.getInstance(JetPackApplication.instance)
//            .beginUniqueWork("test", ExistingWorkPolicy.APPEND_OR_REPLACE,request)
            .beginWith(request)
            .enqueue()
//            .enqueue()

//        WorkManager.getInstance(JetPackApplication.instance).cancelAllWorkByTag("test")
    }
}


class TestWorker(context: Context, workerParameters: WorkerParameters): Worker(context, workerParameters) {
    override fun doWork(): Result {
        val params1 = inputData.getInt("params1", 0)
        val params2 = inputData.getString("params2")
        Log.d(javaClass.name, "获得参数:$params1,$params2")
        return Result.success()
    }

    override fun onStopped() {
        super.onStopped()
        Log.d(javaClass.name, "onStopped...")
    }
}